package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.commons.exception.AddressException;
import com.woniuxy.commons.exception.code.AddressExceptionCode;
import com.woniuxy.commons.utils.BeanCopyUtil;
import com.woniuxy.controller.form.LoadAddressForm;
import com.woniuxy.controller.form.UpdateAddressForm;
import com.woniuxy.dao.model.AddressInfo;
import com.woniuxy.dao.AddressInfoDao;
import com.woniuxy.service.AddressInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.dto.AllAddressDto;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author psy
 * @since 2022-06-28
 */
@Service
public class AddressInfoServiceImpl extends ServiceImpl<AddressInfoDao, AddressInfo> implements AddressInfoService {
    @Resource
    private AddressInfoService addressInfoService;
    @Override
    public Page<AllAddressDto> loadAddress(LoadAddressForm loadAddressForm) {
        System.out.println(loadAddressForm);
        Page<AddressInfo> addressInfoPage = new Page<AddressInfo>(loadAddressForm.getPageNum(),loadAddressForm.getPageSize());
        Page<AddressInfo> customerId1 = addressInfoService.page(addressInfoPage, new QueryWrapper<AddressInfo>().eq("customerId", loadAddressForm.getCustomerId()));

        if(null==customerId1){
            return null;
        }else{
            Page<AllAddressDto> allAddressDtoPage = BeanCopyUtil.copyPageInfo(customerId1,AllAddressDto.class);
            System.out.println(allAddressDtoPage.getPages());
            return allAddressDtoPage;
        }
    }

    @Override
    public boolean delAddress(Long customerId) {
        ArrayList<AddressInfo> addressInfos= (ArrayList<AddressInfo>) addressInfoService.list((new QueryWrapper<AddressInfo>().eq("customerId", customerId)));
        System.out.println(addressInfos);
        boolean customerId1 = addressInfoService.remove(new QueryWrapper<AddressInfo>().eq("customerId", customerId));
        if(addressInfos.size()==0||customerId1){
            return true;
        }else{
            throw new AddressException(AddressExceptionCode.ADDRESS_DEL_NOT_FAIL.getCode(),AddressExceptionCode.ADDRESS_DEL_NOT_FAIL.getMessage());
        }
    }

    @Override
    public boolean updateAddress(UpdateAddressForm updateAddressForm) {
        AddressInfo addressInfo = BeanCopyUtil.copyOne(updateAddressForm, AddressInfo.class);
        boolean save = addressInfoService.save(addressInfo);
        if(save){
            return true;
        }else{
            throw new AddressException(AddressExceptionCode.ADDRESS_UPDATE_FAIL.getCode(),AddressExceptionCode.ADDRESS_UPDATE_FAIL.getMessage());
        }
    }
}
